package app

import (
	"gitee.com/zhucheer/orange/view"
)

type viewTmpl struct {
	ShareAssigns    map[string]interface{}
	IncludeTmplName []string
}

func newViewTmpl() *viewTmpl {
	return &viewTmpl{
		ShareAssigns:    make(map[string]interface{}),
		IncludeTmplName: make([]string, 0),
	}
}

// AddIncludeTmpl添加引入模版
func (c *Context) AddIncludeTmpl(viewName string) {
	c.mutx.Lock()
	defer c.mutx.Unlock()
	c.view.IncludeTmplName = append(c.view.IncludeTmplName, viewName)
}

// ShareAssign 全局通用模板变量
func (c *Context) ShareAssign(key string, viewData interface{}) {
	if c.view == nil {
		panic("viewTmpl not init")
	}
	c.mutx.Lock()
	defer c.mutx.Unlock()
	c.view.ShareAssigns[key] = viewData

	return
}

// ViewHtml 快速渲染html视图
func (c *Context) ViewHtml(viewName string, viewDatas ...interface{}) error {
	tmpl := view.ContextTmpl(viewName, c.view.IncludeTmplName...)
	for _, item := range viewDatas {
		tmpl = tmpl.Assigns(item)
	}

	c.putAssignVar(tmpl)
	htmlRes, err := tmpl.Render()
	if err != nil {
		c.HttpError(err.Error(), 500)
		return err
	}
	c.ResponseReset()
	c.ResponseWrite([]byte(htmlRes))
	return nil
}

// ViewHtml 快速渲染text视图
func (c *Context) ViewText(viewName string, viewDatas ...interface{}) error {
	tmpl := view.ContextTmpl(viewName, c.view.IncludeTmplName...)
	for _, item := range viewDatas {
		tmpl = tmpl.Assigns(item)
	}

	c.putAssignVar(tmpl)
	htmlRes, err := tmpl.RenderText()

	if err != nil {
		c.HttpError(err.Error(), 500)
		return err
	}
	c.ResponseReset()
	c.response.Header().Set("Content-Type", "text/plain;charset=utf-8")
	c.ResponseWrite([]byte(htmlRes))
	return nil
}

// putDefaultVar 注入系统变量
func (c *Context) putAssignVar(tmpl *view.AppTemplate) {
	c.view.ShareAssigns["CSRF_TOKEN"] = c.CsrfToken
	c.view.ShareAssigns["REQUEST_REFERER"] = c.OrangeInput.Referer()

	tmpl.Assigns(c.view.ShareAssigns)
}
